package com.wl.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.wl.dao.NewsInfoDao;
import com.wl.enums.Status;
import com.wl.model.NewsInfo;
import com.wl.service.NewsService;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * Created by wu on 2018/4/18.
 */
@Service("newsServiceImpl")
public class NewsServiceImpl implements NewsService {
    @Autowired
    private NewsInfoDao newsInfoDao;

    @Override
    public Pair<Integer, List<NewsInfo>> newsInfoList(Integer page, Integer pageSize, String title, String status) {
        List<NewsInfo> list;
        Wrapper<NewsInfo> wrapper = new EntityWrapper<NewsInfo>();
        if (!title.isEmpty()) {
            wrapper.like("title", "%" + title + "%");
        }
        if (!status.isEmpty()) {
            wrapper.eq("status", status);
        }
        if (page != null && pageSize != null) {
            RowBounds rowBounds = new RowBounds((page - 1) * pageSize, pageSize);
            list = newsInfoDao.selectPage(rowBounds, wrapper);
        } else {
            list = newsInfoDao.selectList(wrapper);
        }
        Integer total = newsInfoDao.selectCount(wrapper);
        Pair<Integer, List<NewsInfo>> of = Pair.of(total, list);
        return of;
    }

    @Transactional
    @Override
    public NewsInfo add(NewsInfo newsInfo, Long userId) {
        newsInfo.setNewsId(null);
        newsInfo.setStatus(Status.enabled.name());
        newsInfo.setCreateBy(userId);
        newsInfo.setCreateTime(new Date());
        newsInfo.setUpdateBy(userId);
        newsInfo.setUpdateTime(new Date());
        newsInfoDao.insert(newsInfo);
        return newsInfo;
    }

    @Transactional
    @Override
    public NewsInfo del(Long newsId, Long userId) {
        NewsInfo newsInfo = newsInfoDao.selectById(newsId);
        newsInfo.setStatus(Status.disabled.name());
        newsInfo.setUpdateBy(userId);
        newsInfo.setUpdateTime(new Date());
        newsInfoDao.updateById(newsInfo);
        return newsInfo;
    }
}
